var config_value=0;
$(function () {
    let buttonGroup = [
        {
            id: 'btn_search',
            size: 'small',
            text: '查询',
            iconCls: 'icon-search',
            onClick: btn_search,
            plain: true
        },
        {
            id: 'btn_export',
            size: 'small',
            text: '导出Excel',
            iconCls: 'icon-page_excel',
            plain: true,
            onClick: btn_export_excel
        },
        {
            id: 'btn_cancel_filter',
            size: 'small',
            text: '清除过滤',
            iconCls: 'icon-clear',
            plain: true,
            onClick: btn_cancel_filter
        },
        {
            id: 'btn_print',
            size: 'small',
            text: '打印发货单',
            iconCls: 'icon-print',
            plain: true,
            onClick: btn_print
        },
        {
            id: 'btn_grid_columns',
            size: 'small',
            text: '列',
            iconCls: 'icon-text_columns',
            plain: true,
            onClick: btn_open_column_list
        },
        // {
        //     id: 'btn_cancel_audit',
        //     size: 'small',
        //     disabled: true,
        //     text: '消审',
        //     iconCls: 'icon-exclamation',
        //     onClick: btn_cancel_audit,
        //     plain: true
        // },
        {
            id: 'btn_close', size: 'small', text: '关闭', iconCls: 'icon-no', onClick: btn_close,
            plain: true
        },
    ];
    buttonGen($('#north'), buttonGroup);
    bindEnterEvents();

    setgrid();  // 预发货网格
    setgrid_ck(); // 库存明细网格
    setgrid_fh();  // 发货明细网格

    setcombox();  // 设置下拉

    $.ajax({
        url: "sysConfigInt/listQuery",
        type: 'get',
        dataType: 'json',
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            // console.log(cdata);
            for(let i = 0;i<cdata.length;i++){
                if (cdata[i].configField==='发货单打印样式'){
                    config_value=cdata[i].configValue
                }
            }
        }
    });

})

//设置下拉
function setcombox() {
    $.ajax({
        url: "contactCompany/listQuery",
        type: 'get',
        dataType: 'json',
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            // console.log(cdata);
            $('#client').combobox({
                data:cdata,
                limitToList:true,
                valueField:'companyName',
                textField:'companyName'
            });
            $('#client_main').combobox({
                data:cdata,
                limitToList:true,
                valueField:'companyName',
                textField:'companyName'
            });
            $('#client_detail').combobox({
                data:cdata,
                limitToList:true,
                valueField:'companyName',
                textField:'companyName'
            });
        }
    });
}

//  选中事件
function onSelect(title, index) {
    function state(f) {
        if (f) {
            $('#start').datebox('disable');
            $('#end').datebox('disable');
        } else {
            $('#start').datebox('enable');
            $('#end').datebox('enable');
        }
    }

    switch (index) {
        case 2:
            if ($('#v_grid').data('kendoGrid') == undefined) {
                grid_1();
            }
            state(false);
             getgriddata(0);

            break;
        case 0:
            if ($('#v_grid_1').data('kendoGrid') == undefined) {
                grid_2();
            }
            state(false);
            getgriddata(1);
            break;
        case 1:
            if ($('#v_grid_2').data('kendoGrid') == undefined) {
                grid_3();
            }
            state(true);
            getgriddata(2);
            break;
    }
}

//报表数据源
function getgriddata(val) {
    var kGrid = getSelectedGrid();
    $.messager.progress({title: '', msg: '请稍等...', interval: 5000});
    $.ajax({
        url: "customize/callProc",
        type: 'post',
        data: JSON.stringify(['p_dye_delivery_report',$('#start').datebox('getValue'),$('#end').datebox('getValue'),val]),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            let  data=cdata.data;
            console.log(data);
            kGrid.dataSource.data(data);

        }, complete: function () {
            $.messager.progress('close');
        }

    })
}

/**
 * 2021年8月11日 11:06:32 chanchaw
 * 成品管理 - 第一个标签页 - 色布发货
 */
function grid_1() {
    let SUFFIX = "_a";
    let billcode = new kendo.data.DataSource({data: []});
    let datafh = new kendo.data.DataSource({data: []});
    let product_name = new kendo.data.DataSource({data: []});
    let specification = new kendo.data.DataSource({data: []});
    let color = new kendo.data.DataSource({data: []});
    let color_no = new kendo.data.DataSource({data: []});
    let memo = new kendo.data.DataSource({data: []});
    let address = new kendo.data.DataSource({data: []});
    let client = new kendo.data.DataSource({data: []});
    let manager = new kendo.data.DataSource({data: []});
    let carnumber = new kendo.data.DataSource({data: []});
    let dataSource = new kendo.data.DataSource({
        // transport: {
        //     read: {
        //         url: "dyeFabricDelivery/report/fhdtl",
        //         dataType: "json",
        //         type: "GET",
        //         data: {
        //             start: $('#start').datebox('getValue'),
        //             end: $('#end').datebox('getValue'),
        //             clientName: $('#contactCompanyId').combobox('getValue'),
        //             // checkType: $('#type').combobox('getValue')
        //             // textField: $('#column').combobox('getValue'),
        //             // valueField: $('#value').textbox('getValue'),
        //         }
        //     }
        // },
        schema: {
            model: {
                fields: {
                    ps: {type: "number"},
                    qty: {type: "number"},
                    meter: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "ps", aggregate: "sum"},
            {field: "qty", aggregate: "sum"},
            {field: "meter", aggregate: "sum"},
        ],
        change: function (e) {
            // let data = this.data();
            //获取过滤条件
            let filtrer = this.filter();
            //获取所有数据
            let allData = this.data();
            //进行过滤条件的筛选
            let query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            let data = query.filter(filtrer).data;

            client.data(unique(data, 'client'));
            billcode.data(unique(data, 'billcode'));
            product_name.data(unique(data, 'product_name'));
            specification.data(unique(data, 'specification'));
            color.data(unique(data, 'color'));
            color_no.data(unique(data, 'color_no'));
            memo.data(unique(data, 'memo'));
            manager.data(unique(data, 'manager'));
            carnumber.data(unique(data, 'carnumber'));
            address.data(unique(data, 'carnumber'));

        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })
        }
    });
    let columns = [
        {field: "no", title: "#", filterable: false, template: "<span class='row_number'></span>", width: 40},
        {
            field: "id",
            title: '编号',
            width: 93,
            hidden: true,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
        },
        // {
        //     field: "client",
        //     title: '客户',
        //     width: 93,
        //     attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;'},
        //     headerAttributes: {'style': 'text-align:center;'},
        //     footerAttributes: {'style': 'color: red;text-align:center;'},
        //     filterable: false
        // },
        {
            field: "billcode",
            title: '发货单号',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {checkAll: true, multi: true, search: true, dataSource: billcode}
        },
        {
            field: "datafh",
            title: '发货时间',
            width: 85,
            // format: "{0: MM-dd HH:mm}",
            headerAttributes: {'style': 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: datafh}
        },
        {
            field: "client",
            title: '客户',
            width: 85,
            headerAttributes: {'style': 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: client}
        },
        {
            field: "product_name",
            title: '品名',
            width: 85,
            // format: "{0: MM-dd HH:mm}",
            headerAttributes: {'style': 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: product_name}
        },
        {
            field: "specification",
            title: '规格',
            width: 85,
            // format: "{0: MM-dd HH:mm}",
            headerAttributes: {'style': 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: specification}
        },
        {
            field: "color",
            title: '颜色',
            width: 85,
            // format: "{0: MM-dd HH:mm}",
            headerAttributes: {'style': 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: color}
        },
        {
            field: "ps",
            title: '匹数',
            width: 93,
            template: item => item['ps'] ? parseFloat(item['ps']).toFixed(0) : '',
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "qty",
            title: '重量',
            width: 93,
            template: item => item['qty'] ? parseFloat(item['qty']).toFixed(1) : '',
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "meter",
            title: '米数',
            width: 93,
            template: item => item['meter'] ? parseFloat(item['meter']).toFixed(1) : '',
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "manager",
            title: '经手人',
            width: 80,
            headerAttributes: {'style': 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: manager}
        },
        {
            field: "carnumber",
            title: '车牌号',
            width: 80,
            // format: "{0: MM-dd HH:mm}",
            headerAttributes: {'style': 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: carnumber}
        },
        {
            field: "address",
            title: '收货地址',
            width: 120,
            // format: "{0: MM-dd HH:mm}",
            headerAttributes: {'style': 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: address}
        },
        {
            field: "memo",
            title: '备注',
            width: 150,
            // format: "{0: MM-dd HH:mm}",
            headerAttributes: {'style': 'text-align:center;'},
            attributes: {'class': 'kendo-custum-char'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: memo}
        },


    ];
    let grid = $("#v_grid").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "色布发货序时表.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            let kGrid = $('#v_grid').data('kendoGrid');
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
                let dataItem = kGrid.dataItem($(this));
                if (dataItem['is_audit'] != undefined && !dataItem['is_audit']) {
                    $(this).addClass('kendo-custum-non-checked');
                }
            });
        },
        columnHide: function (e) {
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
        },
        columnShow: function (e) {
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null, SUFFIX);
        },
        columnResize: function (e) {
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null, SUFFIX);
            }
        },
        columnReorder: function (e) {
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field'] + SUFFIX
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_grid').data('kendoGrid');
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    grid01.setOptions({
        columns: columns
    });
    grid.on('dblclick', 'tr', function (e) {
        //  修改单据
        let kGrid = $("#v_grid").data("kendoGrid");
        let dataItem = kGrid.dataItem(e.currentTarget);
        open_fhdetail(dataItem);
    })
    grid.on('click', 'tr', function (e) {
        let kGrid = $("#v_grid").data("kendoGrid");
        let dataItem = kGrid.dataItem(e.currentTarget);
        if (dataItem['is_audit']) {
            $('#btn_cancel_audit').linkbutton('enable')
        } else {
            $('#btn_cancel_audit').linkbutton('disable')
        }
    })
    grid.on('contextmenu', 'tr', function (e) {
        e.preventDefault();
        let kGrid = $('#v_grid').data('kendoGrid');
        var selectedRows = kGrid.select();
        let div = $(`<div class="easyui-menu_01">
                         <div data-options="name:'设置发货',iconCls:'icon-ok'">设置发货(批量)</div>
                         <div data-options="name:'作废',iconCls:'icon-cancel'">作废</div>
                     </div>`);
        $('body').append(div);
        div.menu({
            onClick: function (item) {
                let name = item.text;
                switch (name) {
                    case '设置发货(批量)':
                        let selectedDataItems = [];
                        let yfh_data=[];
                        for (let i = 0; i < selectedRows.length; i++) {
                            let dataItem = kGrid.dataItem(selectedRows[i]);
                            selectedDataItems.push(dataItem.billcode);
                            if (!dataItem.client){
                                let Obj= {"product_name":dataItem.product_name,"material_specification":dataItem.material_specification,"client":dataItem.client,
                                    "ps":dataItem.ps,"qty":dataItem.qty,"billcode":dataItem.billcode};
                                yfh_data.push(Obj);
                            }else{
                                $.messager.alert({title: '提示', msg: "已设置客户不允许选择批量设置！"});
                                return;
                            }
                        }
                        console.log(selectedDataItems);
                        if(yfh_data.length>0){
                            $('#fh_main').dialog('open');
                        }else{
                            $.messager.alert({title: '提示', msg: "未选择数据！！！"});
                        }
                        break;
                    case '作废':
                        if(selectedRows.length>1){
                            $.messager.alert({title: '提示', msg: "作废不允许多选！！！"});
                            return;
                        }
                        if(selectedRows.length>0){
                            $.messager.confirm('确认', '确定作废当前选中发货单吗？不可恢复！', function (r) {
                                if (r) {
                                    $.ajax({
                                        url: "cpBillfh/setVoid",
                                        type: 'post',
                                        data: JSON.stringify({"id":kGrid.dataItem(selectedRows[0]).id}),
                                        contentType: "application/json;charset=UTF-8",
                                        success: function (cdata) {
                                            // let  data=cdata.data;
                                            btn_search();
                                            $.messager.show({title: '提示', msg: "作废发货完成！！！"});
                                        }
                                    });
                                }
                            })

                        }else{
                            $.messager.alert({title: '提示', msg: "未选择数据！！！"});
                        }
                        break;
                }
            },
        });
        div.menu('show', {
            left: e.pageX,
            top: e.pageY
        })
    });
}

/**
 * 2021年8月11日 11:06:32 chanchaw
 * 成品管理 - 第二个标签页 - 色布入库
 */
function grid_2() {
    let SUFFIX = "_b";
    let plan_code = new kendo.data.DataSource({data: []});
    let order_code = new kendo.data.DataSource({data: []});
    let product_name = new kendo.data.DataSource({data: []});
    let material_specification = new kendo.data.DataSource({data: []});
    let color_no = new kendo.data.DataSource({data: []});
    let color = new kendo.data.DataSource({data: []});
    let tube = new kendo.data.DataSource({data: []});
    let B_Class = new kendo.data.DataSource({data: []});
    let b_barcode = new kendo.data.DataSource({data: []});
    let dataSource = new kendo.data.DataSource({
        // transport: {
            // read: {
            //     url: "dyeFabricDelivery/report/dyeFabric/input",
            //     dataType: "json",
            //     type: "GET",
            //     data: {
            //         start: $('#start').datebox('getValue'),
            //         end: $('#end').datebox('getValue'),
            //         clientName: $('#contactCompanyId').combobox('getValue'),
            //         // textField: $('#column').combobox('getValue'),
            //         // valueField: $('#value').textbox('getValue'),
            //     }
            // }
        // },
        schema: {
            model: {
                fields: {
                    ps: {type: "number"},
                    qty: {type: "number"},
                    meter: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "ps", aggregate: "sum"},
            {field: "qty", aggregate: "sum"},
            {field: "meter", aggregate: "sum"},
        ],
        change: function (e) {
            // let data = this.data();
            //获取过滤条件
            let filtrer = this.filter();
            //获取所有数据
            let allData = this.data();
            //进行过滤条件的筛选
            let query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            let data = query.filter(filtrer).data;

            plan_code.data(unique(data, 'plan_code'));
            order_code.data(unique(data, 'order_code'));
            product_name.data(unique(data, 'product_name'));
            material_specification.data(unique(data, 'material_specification'));
            color_no.data(unique(data, 'color_no'));
            color.data(unique(data, 'color'));
            tube.data(unique(data, 'tube'));
            B_Class.data(unique(data, 'B_Class'));
            b_barcode.data(unique(data, 'b_barcode'));

            $('#btn_cancel_audit').linkbutton('disable')
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })

        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })

        }
    });
    let columns = [
        {field: "no", title: "#", filterable: false, template: "<span class='row_number'></span>", width: 40},
        {
            field: "id",
            title: '编号',
            width: 93,
            hidden: true,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
        },
        {
            field: "plan_code",
            title: '计划单号',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: plan_code}
        },
        {
            field: "b_barcode",
            title: '二维码编号',
            width: 100,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: b_barcode}
        },
        {
            field: "product_name",
            title: '品名',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: product_name}
        },
        {
            field: "material_specification",
            title: '规格',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: material_specification}
        },
        {
            field: "color",
            title: '颜色',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: color}
        },
        {
            field: "color_no",
            title: '色号',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: color_no}
        },
        {
            field: "ps",
            title: '匹数',
            width: 93,
            template: item => item['ps'] ? parseFloat(item['ps']).toFixed(0) : '',
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "qty",
            title: '重量',
            width: 93,
            template: item => item['qty'] ? parseFloat(item['qty']).toFixed(1) : '',
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "meter",
            title: '米数',
            width: 93,
            template: item => item['meter'] ? parseFloat(item['meter']).toFixed(1) : '',
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "tube",
            title: '管材',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: tube}
        },
        {
            field: "B_Class",
            title: '质检',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: B_Class}
        },
        {
            field: "B_DTRK",
            title: '入库时间',
            width: 120,
            // format: "{0: MM-dd HH:mm}",
            headerAttributes: {'style': 'text-align:center;'},
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            filterable: false
        },

    ];
    let grid = $("#v_grid_1").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "色布入库序时表.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            let kGrid = $('#v_grid_1').data('kendoGrid');
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
                let dataItem = kGrid.dataItem($(this));
                if (dataItem['is_audit'] != undefined && !dataItem['is_audit']) {
                    $(this).addClass('kendo-custum-non-checked');
                }
            });
        },
        columnHide: function (e) {
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
        },
        columnShow: function (e) {
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null, SUFFIX);
        },
        columnResize: function (e) {
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null, SUFFIX);
            }
        },
        columnReorder: function (e) {
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field'] + SUFFIX
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_grid_1').data('kendoGrid');
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    grid01.setOptions({
        columns: columns
    });
    grid.on('dblclick', 'tr', function (e) {
        //  修改单据
    })
    grid.on('click', 'tr', function (e) {
        let kGrid = $("#v_grid_1").data("kendoGrid");
        let dataItem = kGrid.dataItem(e.currentTarget);
        if (dataItem['is_audit']) {
            $('#btn_cancel_audit').linkbutton('enable')
        } else {
            $('#btn_cancel_audit').linkbutton('disable')
        }
    })
}

/**
 * 2021年8月11日 11:06:32 chanchaw
 * 成品管理 - 第三个标签页 - 色布库存
 */

function grid_3() {
    let SUFFIX = "_b";
    let plan_code = new kendo.data.DataSource({data: []});
    let order_code = new kendo.data.DataSource({data: []});
    let product_name = new kendo.data.DataSource({data: []});
    let material_specification = new kendo.data.DataSource({data: []});
    let color_no = new kendo.data.DataSource({data: []});
    let color = new kendo.data.DataSource({data: []});
    let tube = new kendo.data.DataSource({data: []});
    let B_Class = new kendo.data.DataSource({data: []});
    let b_barcode = new kendo.data.DataSource({data: []});
    let dataSource = new kendo.data.DataSource({
        schema: {
            model: {
                fields: {
                    ps: {type: "number"},
                    qty: {type: "number"},
                    meter: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "ps", aggregate: "sum"},
            {field: "qty", aggregate: "sum"},
            {field: "meter", aggregate: "sum"},
        ],
        change: function (e) {
            // let data = this.data();
            //获取过滤条件
            let filtrer = this.filter();
            //获取所有数据
            let allData = this.data();
            //进行过滤条件的筛选
            let query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            let data = query.filter(filtrer).data;

            plan_code.data(unique(data, 'plan_code'));
            order_code.data(unique(data, 'order_code'));
            product_name.data(unique(data, 'product_name'));
            material_specification.data(unique(data, 'material_specification'));
            color_no.data(unique(data, 'color_no'));
            color.data(unique(data, 'color'));
            tube.data(unique(data, 'tube'));
            B_Class.data(unique(data, 'B_Class'));
            b_barcode.data(unique(data, 'b_barcode'));

            $('#btn_cancel_audit').linkbutton('disable')
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })

        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })

        }
    });
    let columns = [
        {field: "no", title: "#", filterable: false, template: "<span class='row_number'></span>", width: 40},
        {
            field: "id",
            title: '编号',
            width: 93,
            hidden: true,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
        },
        {
            field: "plan_code",
            title: '计划单号',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: plan_code}
        },
        {
            field: "b_barcode",
            title: '二维码编号',
            width: 100,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: b_barcode}
        },
        {
            field: "product_name",
            title: '品名',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: product_name}
        },
        {
            field: "material_specification",
            title: '规格',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: material_specification}
        },
        {
            field: "color",
            title: '颜色',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: color}
        },
        {
            field: "color_no",
            title: '色号',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: color_no}
        },
        {
            field: "ps",
            title: '匹数',
            width: 93,
            template: item => item['ps'] ? parseFloat(item['ps']).toFixed(0) : '',
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "qty",
            title: '重量',
            width: 93,
            template: item => item['qty'] ? parseFloat(item['qty']).toFixed(1) : '',
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "meter",
            title: '米数',
            width: 93,
            template: item => item['meter'] ? parseFloat(item['meter']).toFixed(1) : '',
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "tube",
            title: '管材',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: tube}
        },
        {
            field: "B_Class",
            title: '质检',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: {checkAll: true, multi: true, search: true, dataSource: B_Class}
        },
        {
            field: "B_DTRK",
            title: '入库时间',
            width: 120,
            // format: "{0: MM-dd HH:mm}",
            headerAttributes: {'style': 'text-align:center;'},
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            filterable: false
        },

    ];
    let grid = $("#v_grid_2").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "色布库存序时表.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            let kGrid = $('#v_grid_2').data('kendoGrid');
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
                let dataItem = kGrid.dataItem($(this));
                if (dataItem['is_audit'] != undefined && !dataItem['is_audit']) {
                    $(this).addClass('kendo-custum-non-checked');
                }
            });
        },
        columnHide: function (e) {
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
        },
        columnShow: function (e) {
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null, SUFFIX);
        },
        columnResize: function (e) {
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null, SUFFIX);
            }
        },
        columnReorder: function (e) {
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field'] + SUFFIX
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_grid_2').data('kendoGrid');
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    grid01.setOptions({
        columns: columns
    });
    grid.on('dblclick', 'tr', function (e) {
        //  修改单据
        let kGrid = $("#v_grid_2").data("kendoGrid");
        let dataItem = kGrid.dataItem(e.currentTarget);
        $('#ck_detail').dialog('open');
        getckdetail(0,dataItem.b_barcode)


    });
    grid.on('click', 'tr', function (e) {
        let kGrid = $("#v_grid_2").data("kendoGrid");
        let dataItem = kGrid.dataItem(e.currentTarget);
        if (dataItem['is_audit']) {
            $('#btn_cancel_audit').linkbutton('enable')
        } else {
            $('#btn_cancel_audit').linkbutton('disable')
        }
    });
    grid.on('contextmenu', 'tr', function (e) {
        e.preventDefault();
        let kGrid = $('#v_grid_2').data('kendoGrid');
        var selectedRows = kGrid.select();
        let div = $(`<div class="easyui-menu">
                         <div data-options="name:'生成发货',iconCls:'icon-ok'">生成发货</div>
                     </div>`);
        $('body').append(div);
        div.menu({
            onClick: function (item) {
                let name = item.text;
                switch (name) {
                    case '生成发货':
                        let selectedDataItems = [];
                        let yfh_data=[];
                        for (let i = 0; i < selectedRows.length; i++) {
                            let dataItem = kGrid.dataItem(selectedRows[i]);
                            selectedDataItems.push(dataItem.b_barcode);
                           let Obj= {"product_name":dataItem.product_name,"material_specification":dataItem.material_specification,"color":dataItem.color,
                               "ps":dataItem.ps,"qty":dataItem.qty,'meter':dataItem.meter,"b_barcode":dataItem.b_barcode};
                            yfh_data.push(Obj);
                        }
                        console.log(selectedDataItems);
                        if(yfh_data.length>0){
                            $('#yfh_win').dialog('open');
                            $('#yfh_dg').datagrid('clearSelections');
                            $('#yfh_dg').datagrid('loadData', yfh_data);
                        }else{
                            $.messager.alert({title: '提示', msg: "未选择数据！！！"});
                        }
                        break;
                }
            },
        });
        div.menu('show', {
            left: e.pageX,
            top: e.pageY
        })
    });
}

// 格式化数值字段，保留一位小数
function formatNumber(value, row, index) {
  return parseFloat(value).toFixed(1);
}

//预发货网格
function setgrid() {
    $('#yfh_dg').datagrid({
        data: [],
        striped: true,
        autoSave: false,
        sortable: true,
        fit:true,
        fitColumns:true,
        ctrlSelect:true,
        rownumbers:true,
        remoteSort: false,
        singleSelect: true,
        showFooter: true,
        idField: 'id',
        // height: 850,
        // width: 50,
        columns:[[
            {field: 'product_name', title: '品名', align: 'center'},
            {field: 'material_specification', title: '规格', align: 'center'},
            {field: 'color', title: '颜色', align: 'center'},
            {field: 'ps', title: '匹数', align: 'center'},
            {field: 'qty', title: '重量', align: 'right',formatter: formatNumber},
            {field: 'meter', title: '米数', align: 'right',formatter: formatNumber},
            {field: 'b_barcode', title: '货架号', align: 'center'}
        ]],
        // onDblClickRow: function (Index,row) {//鼠标双击事件
        //     m_gridId=row.iid;
        //     open_win_grid(m_gridId);
        // }
        onLoadSuccess: function (data) {
            compute();
            $(this).datagrid('resize');
            console.log('onLoadSuccess')
        },
        onAfterDeleteRow: function(index, data){
            // 在删除行后触发的事件，你可以在这里进行相关操作
            compute();
            console.log('onAfterDeleteRow')
        },
        onRowContextMenu: function(e, index, row){
            e.preventDefault(); // 阻止默认右键菜单
            $('#yfh_dg').datagrid('selectRow', index); // 选中右键点击的行
            let div = $(`<div class="easyui-menu_yfh">
                         <div data-options="name:'生成发货',iconCls:'icon-cancel'">删除</div>
                     </div>`);
            $('body').append(div);
            div.menu({
                onClick: function (item) {
                    let name = item.text;
                    switch (name) {
                        case '删除':
                            console.log(index);
                            $('#yfh_dg').datagrid('deleteRow',index);
                            compute();
                            break;
                    }
                },
            });
            div.menu('show', {
                left: e.pageX,
                top: e.pageY
            })
        }
    });
}

//已发货明细网格
function setgrid_fh() {
    $('#fh_dg').datagrid({
        striped: true, autoSave: false, sortable: true, fit:true, fitColumns:true, ctrlSelect:true, rownumbers:true, remoteSort: false, singleSelect: true, showFooter: true,
        columns:[[
            {field: 'B_ItemID', title: '打卷主键', align: 'center',hidden:true},
            {field: 'ph', title: '匹号', align: 'center'},
            {field: 'qty', title: '重量', align: 'right',width:80,formatter: formatNumber},
            {field: 'meter', title: '米数', align: 'right',width:80,formatter: formatNumber},
            {field: 'qrcode', title: '二维码编号', align: 'center'},
            {field: 'b_barcode', title: '货架号', align: 'center'}
        ]],
        // onDblClickRow: function (Index,row) {//鼠标双击事件
        //     m_gridId=row.iid;
        //     open_win_grid(m_gridId);
        // }
        onLoadSuccess: function (data) {
            compute_fh()
            $(this).datagrid('resize');
        },
        onAfterDeleteRow: function(index, data){
            // 在删除行后触发的事件，你可以在这里进行相关操作
        },
        onRowContextMenu: function(e, index, row){
            e.preventDefault(); // 阻止默认右键菜单
            $('#ck_dg').datagrid('selectRow', index); // 选中右键点击的行
            let div = $(`<div class="easyui-menu_fh">
                         <div data-options="name:'删除',iconCls:'icon-cancel'">删除</div>
                     </div>`);
            $('body').append(div);
            div.menu({
                onClick: function (item) {
                    let name = item.text;
                    switch (name) {
                        case '删除':
                            $.messager.confirm('确认', '确定删除当前选中数量吗？不可恢复', function (r) {
                                if (r) {
                                    console.log(row);
                                    $.ajax({
                                        url: "gjrkbillCp/clearFPDIDOne",
                                        type: 'post',
                                        data: JSON.stringify({"jrkId":row.B_ItemID}),
                                        contentType: "application/json;charset=UTF-8",
                                        success: function (cdata) {
                                            console.log(cdata);
                                            if (cdata.code===1){
                                                $('#fh_dg').datagrid('deleteRow',index);
                                                btn_search();
                                                compute_fh();
                                                $.messager.show({title: '提示', msg: "删除发货明细成功！"})
                                            }
                                        }
                                    });
                                }
                            })
                            break;
                    }
                },
            });
            div.menu('show', {
                left: e.pageX,
                top: e.pageY
            })
        }
    });
}

//库存明细网格
function setgrid_ck() {
    $('#ck_dg').datagrid({
        striped: true, autoSave: false, sortable: true, fit:true, fitColumns:true, ctrlSelect:true, rownumbers:true, remoteSort: false, singleSelect: true, showFooter: true,
        columns:[[
            {field: 'B_ItemID', title: '打卷主键', align: 'center',hidden:true},
            {field: 'ph', title: '匹号', align: 'center'},
            {field: 'qty', title: '重量', align: 'right',width:80,formatter: formatNumber},
            {field: 'meter', title: '米数', align: 'right',width:80,formatter: formatNumber},
            {field: 'qrcode', title: '二维码编号', align: 'center'}
        ]],
        // onDblClickRow: function (Index,row) {//鼠标双击事件
        //     m_gridId=row.iid;
        //     open_win_grid(m_gridId);
        // }
        onLoadSuccess: function (data) {
            compute_ck();
            $(this).datagrid('resize');
        },
        onRowContextMenu: function(e, index, row){
            e.preventDefault(); // 阻止默认右键菜单
            $('#ck_dg').datagrid('selectRow', index); // 选中右键点击的行
            let div = $(`<div class="easyui-menu_ck">
                         <div data-options="name:'删除',iconCls:'icon-cancel'">删除</div>
                     </div>`);
            $('body').append(div);
            div.menu({
                onClick: function (item) {
                    let name = item.text;
                    switch (name) {
                        case '删除':
                            $.messager.confirm('确认', '确定删除当前选中数量吗？不可恢复', function (r) {
                                if (r) {
                                    console.log(row);
                                    $.ajax({
                                        url: "gjrkbillCp/delete/"+row.B_ItemID,
                                        type: 'post',
                                        dataType: 'json',
                                        contentType: "application/json;charset=UTF-8",
                                        success: function (cdata) {
                                            console.log(cdata);
                                            if (cdata.code===1){
                                                $('#ck_dg').datagrid('deleteRow',index);
                                                btn_search();
                                                compute_ck();
                                                $.messager.show({title: '提示', msg: "删除库存明细成功！"})
                                            }
                                        }
                                    });
                                }
                            })
                            break;
                    }
                },
            });
            div.menu('show', {
                left: e.pageX,
                top: e.pageY
            })
        }
    });
}
//合计
function compute() {
    let rows = $("#yfh_dg").datagrid("getRows");
    let ps = 0, qty = 0,meter=0;
    for (let i = 0; i < rows.length; i++) {
        ps += parseFloat(rows[i].ps ? rows[i].ps : 0);
        qty += parseFloat(rows[i].qty ? rows[i].qty : 0);
        meter += parseFloat(rows[i].meter ? rows[i].meter : 0);
    }
    $("#yfh_dg").datagrid('reloadFooter', [
        {
            product_name: '合计',
            ps: ps,
            qty: qty.toFixed(1),
            meter:meter.toFixed(1),
        }
    ]);
}

function compute_fh() {
    let rows = $("#fh_dg").datagrid("getRows");
    let ps = 0, qty = 0,meter=0;
    for (let i = 0; i < rows.length; i++) {
        ps += 1;
        qty += parseFloat(rows[i].qty ? rows[i].qty : 0);
        meter += parseFloat(rows[i].meter ? rows[i].meter : 0);
    }
    $("#fh_dg").datagrid('reloadFooter', [{ph: ps, qty: qty.toFixed(1),meter: meter.toFixed(1)}]);
}

function compute_ck() {
    let rows = $("#ck_dg").datagrid("getRows");
    let ps = 0, qty = 0,meter=0;
    for (let i = 0; i < rows.length; i++) {
        ps += 1;
        qty += parseFloat(rows[i].qty ? rows[i].qty : 0);
        meter += parseFloat(rows[i].meter ? rows[i].meter : 0);
    }
    $("#ck_dg").datagrid('reloadFooter', [{ph: ps, qty: qty.toFixed(1), meter: meter.toFixed(1)}]);
}

/************************************************************
 */
//预发货设置
function close_yfh() {
    $('#yfh_win').dialog('close');

    $('#client').combobox('setValue',"");
    $('#manager').textbox('setValue',"");
    $('#carnumber').textbox('setValue',"");
    $('#memo').textbox('setValue',"");
    $('#address').textbox('setValue',"");

}

function save_yfh() {
    var client = $('#client').combobox('getValue');
    var manager = $('#manager').textbox('getValue');
    var carnumber = $('#carnumber').textbox('getValue');
    var address= $('#address').textbox('getValue');
    var memo = $('#memo').textbox('getValue');
    // 获取datagrid中的所有数据
    var allData = $('#yfh_dg').datagrid('getData');
    if (allData.rows.length>0){}else{$.messager.alert({title: '提示', msg: "库存为空！"});return;}
    if (client.length>0){}else{$.messager.alert({title: '提示', msg: "客户不允许为空！"});return;}

    let shelveList=[];
    let fhdObj={"client":client,"manager":manager,"carnumber":carnumber,"address":address,"memo":memo};
    for (let i=0;i<allData.rows.length;i++){
        shelveList.push(allData.rows[i].b_barcode)
    }
    let strData={"fhd":fhdObj,"shelveList":shelveList};
    console.log(strData);
    $.ajax({
        url: "cpBillfh/insert8ShelvesListClient",
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(strData),
        // data:{"jrkId":50,"deviceId":223},
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            // let data=cdata.data;
            console.log(cdata);
            $.messager.show({title: '提示', msg: "生成发货单完成！！！"});
            close_yfh();
            // getgriddata(2);
            $('#tabs').tabs('select', 2);
        }
    });
}

/************************************************************
 *
 */
//已生成发货单 设置抬头 批量修改
function save_main() {
    var client = $('#client_main').combobox('getValue');
    var manager = $('#manager_main').textbox('getValue');
    var carnumber = $('#carnumber_main').textbox('getValue');
    var address= $('#address_main').textbox('getValue');
    var memo = $('#memo_main').textbox('getValue');

    let strSQL=[];
    let kGrid = $('#v_grid').data('kendoGrid');
    var selectedRows = kGrid.select();
    for (let i = 0; i < selectedRows.length; i++) {
        let dataItem = kGrid.dataItem(selectedRows[i]);

        let Obj= {"id":dataItem.id,"client":client,"manager":manager, "carnumber":carnumber,"address":address,"memo":memo};
        strSQL.push(Obj);
    }

   console.log(strSQL);

    $.ajax({
        url: "cpBillfh/multiUpdate",
        type: 'post',
        data: JSON.stringify(strSQL),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            // let  data=cdata.data;
           console.log('批量修改返回值：',cdata);
            close_main();
            btn_search();
        }
    });

}
function saveprint_main() {
    close_main()
}
function close_main() {
    $('#fh_main').dialog('close');

    $('#client_main').combobox('setValue',"");
    $('#manager_main').textbox('setValue',"");
    $('#carnumber_main').textbox('setValue',"");
    $('#memo_main').textbox('setValue',"");
    $('#address_main').textbox('setValue',"");
}
/************************************************************
 * */

function close_cpdetail() {
    $('#ck_detail').dialog('close');
    // btn_search()
}
/************************************************************
 * */

//关闭发货明细 窗口
function close_fhdetail() {
    $('#fh_detail').dialog('close');
    // btn_search()
}
//打开发货明细 窗口
function open_fhdetail(dataItem) {
    $('#fh_barcode').textbox('setValue',dataItem.billcode);
    $('#client_detail').combobox('setValue',dataItem.client);
    $('#manager_detail').textbox('setValue',dataItem.manager);
    $('#carnumber_detail').textbox('setValue',dataItem.carnumber);
    $('#memo_detail').textbox('setValue',dataItem.memo);
    $('#address_detail').textbox('setValue',dataItem.address);

    $('#fh_detail').dialog('open');
    getckdetail(dataItem.id,0)
}
// 设置发货单明细抬头数据 单个发货单修改
function save_fhdetail() {
    var client = $('#client_detail').combobox('getValue');
    var manager = $('#manager_detail').textbox('getValue');
    var carnumber = $('#carnumber_detail').textbox('getValue');
    var memo= $('#memo_detail').textbox('getValue');
    var address = $('#address_detail').textbox('getValue');

    let strSQL=[];
    let kGrid = $('#v_grid').data('kendoGrid');
    var selectedRows = kGrid.select();
    for (let i = 0; i < selectedRows.length; i++) {
        let dataItem = kGrid.dataItem(selectedRows[i]);

        let Obj= {"id":dataItem.id,"client":client,"manager":manager, "carnumber":carnumber,"address":address,"memo":memo};
        strSQL.push(Obj);
    }

    console.log(strSQL);

    $.ajax({
        url: "cpBillfh/multiUpdate",
        type: 'post',
        data: JSON.stringify(strSQL),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            // let  data=cdata.data;
            console.log('修改明细返回值：',cdata);
            close_fhdetail();
            btn_search();
        }
    });
}

/************************************************************
 * */

//库存明细获取数据
function getckdetail(m_FPDID,m_barcode) {
    $.messager.progress({title: '', msg: '请稍等...', interval: 5000});
    $.ajax({
        url: "customize/callProc",
        type: 'post',
        data: JSON.stringify(['usp_getcpjrkdetail',m_FPDID,m_barcode]),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            let  data=cdata.data;
            if (Number(m_FPDID)>0){
                $('#fh_dg').datagrid('clearSelections');
                $('#fh_dg').datagrid('loadData', data);
            }else{
                $('#ck_dg').datagrid('clearSelections');
                $('#ck_dg').datagrid('loadData', data);
            }
        }, complete: function () {
            $.messager.progress('close');
        }

    })

}
//清除过滤
function btn_cancel_filter() {
    switch (getCurrentIndex()) {
        case 0:
            $('#v_grid_1').data('kendoGrid').dataSource.filter({});
            break;
        case 1:
            $('#v_grid_2').data('kendoGrid').dataSource.filter({});
            break;
        case 2:
            $('#v_grid').data('kendoGrid').dataSource.filter({});
            break;
        // case 3:
        //     $('#v_grid_3').data('kendoGrid').dataSource.filter({});
        //     break;
        // case 4:
        //     $('#v_grid_4').data('kendoGrid').dataSource.filter({});
        //     break;
    }
    $('#v_grid').data('kendoGrid').dataSource.filter({});
}
//查询事件
function btn_search() {
    switch (getCurrentIndex()) {
        case 0:
            getgriddata(0);
            break;
        case 1:
            getgriddata(1);
            break;
        case 2:
            getgriddata(2);
            break;
    }
}

/********************************************
 */
//获取标签页序号
function getCurrentIndex() {
    let tab = $('#tabs').tabs('getSelected');
    let index = $('#tabs').tabs('getTabIndex', tab);
    return index;
}
//获取当前标签页的网格对象
function getSelectedGrid() {
    let kendoGridID = '';
    switch (getCurrentIndex()) {
        case 0:
            kendoGridID = '#v_grid_1';
            break;
        case 1:
            kendoGridID = '#v_grid_2';
            break;
        case 2:
            kendoGridID = '#v_grid';
            break;
    }
    return $(kendoGridID).data('kendoGrid');
}
//打印
function btn_print() {
    let reportlets = [];
    $.get('customize/getDatabase', {}, data => {
        if (data.success) {
            switch (getCurrentIndex()) {
                case 2:
                    let kGrid = $('#v_grid').data('kendoGrid');
                    var selectedRows = kGrid.select();
                    if (config_value===1 || config_value===2){
                        // 正常打印发货单，打印单公斤数、或者单米数
                        for (let i = 0; i < selectedRows.length; i++) {
                            let dataItem = kGrid.dataItem(selectedRows[i]);
                            if (dataItem.client){
                                let Obj= {
                                    reportlet: config_value===1?`${data.data}/invoice-fhd01.cpt`:`${data.data}/invoice-fhd02.cpt`,
                                    id: dataItem.id,
                                    database: data.data
                                };
                                reportlets.push(Obj);
                            }else{
                                $.messager.alert({title: '提示', msg: "未设置客户，不允许打印！"});
                                return;
                            }

                        }
                    }else{
                        //同时打印 重量和米数
                        for (let i = 0; i < selectedRows.length; i++) {
                            let dataItem = kGrid.dataItem(selectedRows[i]);
                            if (dataItem.client){
                                let ordernumber=0,ordersum=0;
                                let inputVariable = Number(dataItem.ps);
                                // 获取商
                                let quotient = Math.floor(inputVariable / 50);
                                // 获取余数
                                let remainder = inputVariable % 50;

                                if (remainder>0){ordersum=quotient+1}else{ordersum=quotient}  // 计算需要分几页打印

                                for (let n=0;n<ordersum;n++){
                                    let Obj= {
                                        reportlet:ordersum-n===1?`${data.data}/invoice-fhd03_01.cpt`: `${data.data}/invoice-fhd03.cpt`,
                                        id: dataItem.id,
                                        ordernumber: n+1,
                                        ordersum: ordersum,
                                        database: data.data
                                    };
                                    reportlets.push(Obj);
                                }

                            }else{
                                $.messager.alert({title: '提示', msg: "未设置客户，不允许打印！"});
                                return;
                            }

                        }

                    }


                    console.log(reportlets);
                    window.parent.FR.doURLPDFPrint({
                        url: $(window.parent.document.body).data('report_url'),
                        isPopUp: false,
                        data: {
                            reportlets: reportlets
                        }
                    })
                    break;

            }
        }
    }, 'json');
}

//z自动列设置
function btn_open_column_list() {
    let kendoGridID = '';
    switch (getCurrentIndex()) {
        case 2:
            kendoGridID = '#v_grid';
            break;
        case 0:
            kendoGridID = '#v_grid_1';
            break;
        case 1:
            kendoGridID = '#v_grid_2';
            break;
        case 3:
            kendoGridID = '#v_grid_3';
            break;
        case 4:
            kendoGridID = '#v_grid_4';
            break;
    }
    let options = $(kendoGridID).data('kendoGrid').getOptions().columns;
    if ($('#btn_open_column_list').length <= 0) {
        let div = $(`<div data-options="resizable:true,iconCls:'icon-text_columns',width:200,height:300,modal:true,title:'列',
                                         onClose:function(){$(this).dialog('destroy')}   " 
                          class="easyui-dialog" id="btn_open_column_list">
                   </div>`);
        let form = $('<form style="width: 100%;height: 100%;"></form>')
        for (let i of options) {
            if (i.field) {
                let checkbox = $(`<div style="width: 100%;height: auto;padding: 5px;">
                <input class="easyui-checkbox" name="${i.field}" data-options="label:'${i.title}',
                labelWidth:120,value:true,name:'${i.field}'">
                </div>`);
                form.append(checkbox);
            }
        }
        let container = $(`<div></div>`);
        form.appendTo(div);
        div.appendTo(container);
        $('body').append(container);
        $.parser.parse($('#btn_open_column_list').parent());
        let formData = {};
        options.map(item => {
            formData[item['field']] = item['hidden'] == undefined ? true : !item['hidden'];
        })
        $('#btn_open_column_list form').eq(0).form('load', formData);
        $('#btn_open_column_list form .easyui-checkbox').each(function () {
            //  绑定事件
            $(this).checkbox({
                onChange: function (checked) {
                    let opts = $(this).checkbox('options');
                    if (checked) {
                        $(kendoGridID).data('kendoGrid').showColumn(opts.name);
                    } else {
                        $(kendoGridID).data('kendoGrid').hideColumn(opts.name);
                    }
                }
            })
        })
    } else {
        $('#btn_open_column_list').dialog('open');
    }
}
//导出
function btn_export_excel() {
    switch (getCurrentIndex()) {
        case 2:
            $('#v_grid').data('kendoGrid').saveAsExcel();
            break;
        case 0:
            $('#v_grid_1').data('kendoGrid').saveAsExcel();
            break;
        case 1:
            $('#v_grid_2').data('kendoGrid').saveAsExcel();
            break;
        case 3:
            $('#v_grid_3').data('kendoGrid').saveAsExcel();
            break;
        case 4:
            $('#v_grid_4').data('kendoGrid').saveAsExcel();
            break;
    }
}


function btn_close() {
    window.parent.closeTab();
}
